import Taro, { Component, Config } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { Loading } from "@/components/index"
import {AUTH_TOKEN, SOURCE_ID} from "@/config/storage";
import {codeToUser, weChartLogin} from "@/api/oauthApi";
import {setUserTokenStorage} from "@/utils/storage";

export default class Index extends Component {
  state: any

  config: Config = {
    navigationBarTitleText: '用户授权'
  }

  componentWillMount() {
    //  写入小程序用户分享参数
    const { params: { code } }:any = this.$router

    if (!code) {
      window.location.href = '/'
    }

    this.codeToToken(code)
  }

  async codeToToken(code) {
    const sourceId = Taro.getStorageSync(SOURCE_ID)
    await codeToUser(code).then(({ data }) => {
      Taro.setStorageSync('AUTH_ORIGINAL', data)
      const { original: { openid, unionid }, nickname, avatar } = data
      Taro.setStorageSync('OPEN_ID', openid)
      weChartLogin({
        openId: openid,
        nickName: nickname,
        headImg: avatar,
        unionId: unionid,
        sourceId
      }).then(({ data }) => {
        setUserTokenStorage(data)
        Taro.setStorageSync(AUTH_TOKEN, data)
        window.location.href = '/'
      })
    })
  }

  render() {
    return (<View className='login-page xf-page d-f f-g-5'>
      <Loading />
    </View>)
  }
}
